package org.aj.web.exception;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * description 监听web容器启动
 *
 * @author jcj
 * date 2022/9/7 15:55
 */
public class WebContainerInitListener implements ApplicationListener<WebServerInitializedEvent> {


    //由调用者来决定使用哪个日志框架
    private static final Log log = LogFactory.getLog(WebContainerInitListener.class);
    /**
     * 记录服务器端口
     */
    private  int serverPort;


    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        this.serverPort=webServerInitializedEvent.getWebServer().getPort();

    }

    public int getServerPort() {
        return serverPort;
    }

    /**
     * description 返回端口号跟主机
     * author aj
     * date 2022/9/7 15:57
     *
     * @return java.lang.String
     */
    public String getHostAndPort(){

        InetAddress address = null;
        try {
            //暂时不考虑双网卡的情况
            address = InetAddress.getLocalHost();
            //拿到主机ip
            String hostAddress = address.getHostAddress();
            //拿到主机名称
            String hostName = address.getHostName();
            if(StringUtils.isBlank(hostName) && StringUtils.isBlank(hostAddress)){
                return "未从当前网卡中获取到主机跟ip地址信息";
            }
            StringBuilder sb = new StringBuilder();
            if(StringUtils.isNotBlank(hostName)){
                sb.append(hostName);
                sb.append(":");
            }
            if(StringUtils.isNotBlank(hostAddress)){
                sb.append(hostAddress);
                sb.append(":");
            }
            sb.append(serverPort);
            return sb.toString();
        } catch (UnknownHostException e) {
            log.error("获取网卡信息失败",e);
            return "未获取到主机信息";
        }
    }
}
